package com.quan.weixin.wx.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.quan.common.base.bean.ResultBean;
import com.quan.common.core.BaseController;
import com.quan.weixin.common.WeixinContext;
import com.quan.weixin.model.QrCodeVo;
import com.quan.weixin.model.SubscribeUser;
import com.quan.weixin.model.UserDetail;
import com.quan.weixin.service.WeixinApiService;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;

@RestController
@RequestMapping("/wx/api")
public class WxApiController extends BaseController {
	
	@Autowired
	private WxMpService wxMpService;

	@GetMapping(value = "/getJsapiTicket")
	public Object getJsapiTicket(String url) {
		try {
			String requestUrl = request.getHeader("Referer") ;
			WxJsapiSignature signature = this.wxMpService.createJsapiSignature(requestUrl);
			return ResultBean.ok(signature) ;
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return ResultBean.failure("调用jsapi时所需要的签名失败") ;
		
	}
	
	@Autowired
	private WeixinApiService apiService ;
	
	/**
	 * 获取关注用户
	 * @param count
	 * @param next_openid
	 * @return
	 */
	@GetMapping(value="/getSubscribeUser")
	public Object getSubscribeUser(int count, String next_openid) {
		SubscribeUser subscribeUser = this.apiService.getSubscribeUserList(WeixinContext.getAccessToken(), next_openid);
		return subscribeUser;
	}
	
	/**
	 * 获取用户基本信息
	 * @param openid
	 * @return
	 */
	@GetMapping(value="/getUserDetail")
	public Object getUserDetail(String openid) {
		UserDetail userDetail = this.apiService.getUserDetail(WeixinContext.getAccessToken(), openid) ;
		return userDetail;
	}
	
	
	/**
	 * 生成临时二维码（604800秒）
	 * @return
	 */
	@GetMapping(value="/showQRCodeTemp")
	public Object showQRCodeTemp(QrCodeVo qrCodeVo) {
		return this.apiService.showQRCodeTemp(WeixinContext.getAccessToken(), qrCodeVo.getExpire_seconds(), qrCodeVo.getAction_name(), qrCodeVo.getSceneValue()) ;
	}
	
	/**
	 * 生成永久二维码（100000个）
	 * @return
	 */
	@GetMapping(value="/showQRCodeForever")
	public Object showQRCodeForever(QrCodeVo qrCodeVo) {
		return this.apiService.showQRCodeForever(WeixinContext.getAccessToken(), qrCodeVo.getAction_name(), qrCodeVo.getSceneValue());
	}
	
}
